package com.aloda.handler;

import com.aloda.exception.BaseException;
import com.aloda.exception.VerifyException;
import com.aloda.exception.WarnException;
import com.aloda.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息:{}", ex.getMessage());
        log.error("异常信息:", ex);
        return Result.error(ex.getErrorCode(),ex.getMessage());
    }

    /**
     * 捕获验证码的异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result verifyExceptionHandler(VerifyException ex){
        log.warn("异常信息:{}", ex.getMessage());
        return Result.error(ex.getErrorCode(), ex.getMessage());
    }

    /**
     *  捕获其它异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result otherExceptionHandler(RuntimeException ex) {
        log.error("异常信息:", ex);
        return Result.error();
    }

    /**
     * 捕获需要警告的异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result warnExceptionHandler(WarnException ex) {
        log.warn("警告信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }
}
